package cn.stylefeng.guns.modular.weixin.controller;

import cn.stylefeng.guns.modular.goods.service.LiuGoodsService;
import cn.stylefeng.guns.modular.goodsCart.model.params.TaoGoodCartParam;
import cn.stylefeng.guns.modular.goodsCart.service.TaoGoodCartService;
import cn.stylefeng.guns.modular.hotgood.model.params.TaoIndexPicParam;
import cn.stylefeng.guns.modular.hotgood.model.result.TaoIndexPicResult;
import cn.stylefeng.guns.modular.hotgood.service.TaoIndexPicService;
import cn.stylefeng.guns.modular.order.model.params.TbFreightParam;
import cn.stylefeng.guns.modular.order.model.params.TbOrderParam;
import cn.stylefeng.guns.modular.order.model.result.TbFreightResult;
import cn.stylefeng.guns.modular.order.service.TbFreightService;
import cn.stylefeng.guns.modular.order.service.TbOrderService;
import cn.stylefeng.guns.modular.recommend.model.params.TaoRecommendGoodsParam;
import cn.stylefeng.guns.modular.recommend.model.result.TaoRecommendGoodsResult;
import cn.stylefeng.guns.modular.recommend.service.TaoRecommendGoodsService;
import cn.stylefeng.guns.modular.weixin.api.PayUtils;
import cn.stylefeng.guns.modular.weixin.entity.Oauth2Token;
import cn.stylefeng.guns.modular.weixin.entity.Profile;
import cn.stylefeng.guns.modular.weixin.entity.SNSUserInfo;
import cn.stylefeng.guns.modular.weixin.service.WeiXinOrderService;
import cn.stylefeng.guns.modular.wxuser.entity.TaoWxUser;
import cn.stylefeng.guns.modular.wxuser.service.TaoWxUserService;
import cn.stylefeng.guns.sys.modular.tao.entity.WxUser;
import cn.stylefeng.guns.sys.modular.tao.model.params.CouponLeadParam;
import cn.stylefeng.guns.sys.modular.tao.model.params.CouponParam;
import cn.stylefeng.guns.sys.modular.tao.model.result.CouponLeadResult;
import cn.stylefeng.guns.sys.modular.tao.model.result.CouponResult;
import cn.stylefeng.guns.sys.modular.tao.service.CouponLeadService;
import cn.stylefeng.guns.sys.modular.tao.service.CouponService;
import cn.stylefeng.guns.sys.modular.tao.service.GoodsService;
import cn.stylefeng.guns.sys.modular.tao.service.WxUserService;
import cn.stylefeng.guns.unitl.NetUtil;
import cn.stylefeng.guns.unitl.WXPayUtil;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller
@RequestMapping("/weixin")
@CrossOrigin("*")
public class WeiXinOrderController extends BaseController {

    @Autowired
    private WeiXinOrderService weiXinOrderService;
    @Autowired
    private LiuGoodsService liuGoodsService;
    @Autowired
    private TbOrderService tbOrderService;
    @Autowired
    private TaoIndexPicService taoIndexPicService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private TaoGoodCartService taoGoodCartService;
    @Autowired
    private CouponLeadService couponLeadService;
    @Autowired
    private WxUserService wxUserService;
    @Autowired
    private TbFreightService tbFreightService;
    @Autowired
    private TaoRecommendGoodsService taoRecommendGoodsService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    private Gson gson;


    /**
     * 微信用户表
     */
    @Autowired
    private TaoWxUserService taoWxUserService;




    @RequestMapping("/selectOrder")
    @ResponseBody
     public List<HashMap<String,String>> selectOrder(@RequestParam("userId")String userId,@RequestParam( value = "status",required = false)String status){
         HashMap<String,String> map=new HashMap<>();
         map.put("userId",userId);
         map.put("status",status);
         return  weiXinOrderService.selectWeixinOrder(map);
     }

    /**
     * 订单拆分
     */
    @RequestMapping("/addOrder")
    @ResponseBody
    public void addOrder(TbOrderParam tbOrderParam){
        String a="1,2,3,4";
        String[] result1 = a.split(",");
        int b=0;
        for (HashMap<String,String> map : liuGoodsService.selectGossId(tbOrderParam)) {
            tbOrderParam.setOrderId(result1[b]+"100");
            tbOrderParam.setGoodsId(map.get("goodsNumber"));
            tbOrderParam.setGoodsName(map.get("goodsName"));
            this.tbOrderService.addOrder(tbOrderParam);
            map.put("inventoryQuantity","1");
            map.put("goodsNumber",result1[b]);
            liuGoodsService.updateInventoryQuantity(map);
            b++;
        }
    }

    /**
     * 登录
     */
    @RequestMapping("/login")
    @ResponseBody
    public Object weiLogin(WxUser wu){
      if(wu.getOpenId() !=null && wu.getOpenId() !=""){
      int count = weiXinOrderService.queryUser(wu.getOpenId());
      return count;
    }
        return "标识符无效";
    }


    /**
     * 注册
     */
    @RequestMapping(value = "/zhuce",method = RequestMethod.POST)
    @ResponseBody
    public Object zhuce(WxUser wu){

        if(weiXinOrderService.WeiUser(wu).size()>0){
            return "n" ;
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String stringDate = sdf.format(date);
        wu.setTimeOn(stringDate);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, 1); //把日期往后增加一年，整数往后推，负数往前移
        date = calendar.getTime();
        stringDate = sdf.format(date);//date-->String
        wu.setTimeOff(stringDate);

        /**
         * 注册时生成 6 位数推广码，并且唯一
         */
        int count = 0;
        String randomNumber = "";
        do{
            randomNumber = String.valueOf((int)((Math.random()*9+1)*100000));
            QueryWrapper<TaoWxUser> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("generalization_code",randomNumber);
            count = taoWxUserService.list(queryWrapper).size();
        }while (count > 0);
        wu.setGeneralizationCode(randomNumber);

        if(ToolUtil.isEmpty(wu.getByGeneralizationCode())){
            wu.setByGeneralizationCode("");
        }else{
            wu.setByGeneralizationCode(wu.getByGeneralizationCode());
        }

        wu.setExtensionState(Long.parseLong("0"));
        weiXinOrderService.zhuce(wu);
        return  "y";
    }


    /**
     *
     *用户修改
     * @return
     */
    @RequestMapping("/updateWxUser")
    @ResponseBody
    public Object uodateWxUser(WxUser wu){

        System.out.println(wu.getId());
        if(weiXinOrderService.WeiUser(wu).size() !=1){
            return "n" ;
        }

        weiXinOrderService.updateWxUser(wu);
        return  "y";
    }


    /**
     * 微信小程序支付
     */
    @RequestMapping(value = {"/WeChatPay"},method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> wxPay(String openid, String money,HttpServletRequest request) {
        //money = String.valueOf(Integer.parseInt(money));
        try {
            String nonce_str = PayUtils.getRandomStringByLength(32);
            String body = "付款";
            String spbill_create_ip = PayUtils.getIpAddr(request);
            String danhao = String.valueOf(System.currentTimeMillis());
            System.out.println(danhao);
            Map<String, String> packageParams = new HashMap();
            //小程序id
            packageParams.put("appid", "wxe09464398e58d00c");
            //商户号id
            packageParams.put("mch_id", "1553191741");
            //随机字符串
            packageParams.put("nonce_str", nonce_str);
            //商品描述
            packageParams.put("body", body);
            //商户订单号
            packageParams.put("out_trade_no", danhao);
            //支付金额
            packageParams.put("total_fee", money);
            //终端ip
            packageParams.put("spbill_create_ip", spbill_create_ip);
            //通知地址
            packageParams.put("notify_url", "http://192.168.0.109:8086/");
            //支付方式
            packageParams.put("trade_type", "JSAPI");
            //支付人唯一标识符
            packageParams.put("openid", openid);
            String prestr = PayUtils.createLinkString(packageParams);
            //商户号密钥
            String mysign = PayUtils.sign(prestr, "chongqingbagendianzishangwuyouxi", "utf-8").toUpperCase();
            String xml = "<xml><appid>wxe09464398e58d00c</appid><body><![CDATA[" + body + "]]></body>" + "<mch_id>" + "1553191741" + "</mch_id>" + "<nonce_str>" + nonce_str + "</nonce_str>" + "<notify_url>" + "http://192.168.0.109:8086/" + "</notify_url>" + "<openid>" + openid + "</openid>" + "<out_trade_no>" + danhao + "</out_trade_no>" + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" + "<total_fee>" + money + "</total_fee>" + "<trade_type>" + "JSAPI" + "</trade_type>" + "<sign>" + mysign + "</sign>" + "</xml>";
            System.out.println("调试模式_统一下单接口 请求XML数据：" + xml);
            String result = PayUtils.httpRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", xml);
            System.out.println("调试模式_统一下单接口 返回XML数据：" + result);
            Map map = PayUtils.doXMLParse(result);
            String return_code = (String)map.get("return_code");
            Map<String, Object> response = new HashMap();
            if (return_code.equals("SUCCESS")) {
                String prepay_id = (String)map.get("prepay_id");
                response.put("nonceStr", nonce_str);
                response.put("package", "prepay_id=" + prepay_id);
                Long timeStamp = System.currentTimeMillis() / 1000L;
                response.put("timeStamp", "" + timeStamp);
                String stringSignTemp = "appId=wxe09464398e58d00c&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
                String paySign = PayUtils.sign(stringSignTemp, "chongqingbagendianzishangwuyouxi", "utf-8").toUpperCase();
                response.put("paySign", paySign);
            }
            response.put("appid", "wxe09464398e58d00c");

            return response;
        } catch (Exception var20) {
            var20.printStackTrace();
            return null;
        }
    }

    /**
     * 微信公众号支付
     */
    @RequestMapping(value = {"/oaPay"},method = {RequestMethod.POST})
    @ResponseBody
    public Map<String, Object> oaPay(String openid, String money,HttpServletRequest request) {
        //money = String.valueOf(Integer.parseInt(money));
        try {
            String nonce_str = PayUtils.getRandomStringByLength(32);
            String body = "付款";
            String spbill_create_ip = PayUtils.getIpAddr(request);
            String danhao = String.valueOf(System.currentTimeMillis());
            System.out.println(danhao);
            String notify_url = "http://back.bgigclub.com/weixin/notify";
            Map<String, String> packageParams = new HashMap();
            //公众号id
            packageParams.put("appid", "wx7a87fd6bafc0dfef");
            //商户号id
            packageParams.put("mch_id", "1553191741");
            //随机字符串
            packageParams.put("nonce_str", nonce_str);
            //商品描述
            packageParams.put("body", body);
            //商户订单号
            packageParams.put("out_trade_no", danhao);
            //支付金额
            packageParams.put("total_fee", money);
            //终端ip
            packageParams.put("spbill_create_ip", spbill_create_ip);
            //通知地址
            packageParams.put("notify_url", notify_url);
            //支付方式
            packageParams.put("trade_type", "JSAPI");
            //支付人唯一标识符
            packageParams.put("openid", openid);
            String prestr = PayUtils.createLinkString(packageParams);
            //商户号密钥
            String mysign = PayUtils.sign(prestr, "chongqingbagendianzishangwuyouxi", "utf-8").toUpperCase();
            String xml = "<xml>" +
                    "<appid>wx7a87fd6bafc0dfef</appid>" +
                    "<body><![CDATA[" + body + "]]></body>" +
                    "<mch_id>" + "1553191741" + "</mch_id>" +
                    "<nonce_str>" + nonce_str + "</nonce_str>" +
                    "<notify_url>" + notify_url + "</notify_url>" +
                    "<openid>" + openid + "</openid>" +
                    "<out_trade_no>" + danhao + "</out_trade_no>" +
                    "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" +
                    "<total_fee>" + money + "</total_fee>" +
                    "<trade_type>" + "JSAPI" + "</trade_type>" +
                    "<sign>" + mysign + "</sign>" +
                    "</xml>";
            System.out.println("调试模式_统一下单接口 请求XML数据：" + xml);
            String result = PayUtils.httpRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST", xml);
            System.out.println("调试模式_统一下单接口 返回XML数据：" + result);
            Map map = PayUtils.doXMLParse(result);
            String return_code = (String)map.get("return_code");
            Map<String, Object> response = new HashMap();
            if (return_code.equals("SUCCESS")) {
                String prepay_id = (String)map.get("prepay_id");
                response.put("nonceStr", nonce_str);
                response.put("package", "prepay_id=" + prepay_id);
                Long timeStamp = System.currentTimeMillis() / 1000L;
                response.put("timeStamp", "" + timeStamp);
                String stringSignTemp = "appId=wx7a87fd6bafc0dfef&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
                String paySign = PayUtils.sign(stringSignTemp, "chongqingbagendianzishangwuyouxi", "utf-8").toUpperCase();
                response.put("paySign", paySign);
            }
            response.put("appid", "wx7a87fd6bafc0dfef");

            return response;
        } catch (Exception var20) {
            var20.printStackTrace();
            return null;
        }
    }

    /**
     * 累加消费金额
     */
    @RequestMapping("/addMoney")
    @ResponseBody
    public ResponseData addMoney(String openid, String money, String num, int i){
        WxUser wxUser = new WxUser();
        if(num.equals("0") ){
            //查询用户消费金额
            wxUser.setOpenId(openid);
            List<WxUser> detail = wxUserService.memberTime(wxUser);
            //已使用总金额
            Double userTotal = detail.get(0).getUseMoney()+Double.parseDouble(money);
            //用户消费金额累计
            wxUserService.updateaddUseMonye(openid, userTotal,0.0);
        }else if (num.equals("1") || num.equals("2") ||num.equals("3") ||num.equals("4") ||num.equals("5")||num.equals("6")){
            //查询用户消费金额
            wxUser.setOpenId(openid);
            List<WxUser> detail = wxUserService.memberTime(wxUser);
            //已使用总金额
            Double userTotal = detail.get(0).getUseMoney()+Double.parseDouble(money);
            Double quotaTotal = 0.0;
            //i=1为会员价，i=0为普通价
            if(i == 1){
                //已使用会员总额度
                quotaTotal = detail.get(0).getQuotaMoney()+Double.parseDouble(money);
            }else if(i == 0){
                quotaTotal = detail.get(0).getQuotaMoney();
            }
            //用户消费金额累计
            wxUserService.updateaddUseMonye(openid, userTotal,quotaTotal);
        }
        return ResponseData.success();
    }

    /**
     * 查询收货地址
     */

    @RequestMapping("/profile")
    @ResponseBody
    public Object profile(Profile profile){

       return   weiXinOrderService.selectProfile(profile);

    }

    /**
     * 增加收货地址
     */

    @RequestMapping("/addProfile")
    @ResponseBody
    public  void addProfile(Profile profile){
        if(profile.getDefaultAddress().equals("true")){
            //先把该用户的所有默认地址修改为 false
            weiXinOrderService.updateAdressByFalse(profile);
        }
        //新增地址
        weiXinOrderService.addProfile(profile);

    }


    /**
     * 修改收货地址
     */

    @RequestMapping("/updateProfile")
    @ResponseBody
    public  void updateProfile(Profile profile){
        //先把该用户的所有默认地址修改为 false
        weiXinOrderService.updateAdressByFalse(profile);
        //更新该用户指定的地址
        weiXinOrderService.updateProfile(profile);

    }


    /**
     *
     * 删除收货地址
     */

    @RequestMapping("/deleteProfile")
    @ResponseBody
    public  void deleteProfile(Profile profile){

        weiXinOrderService.deleteProfile(profile);

    }


    /**
     * 添加购物车
     *
     * @author lcw
     * @Date 2019-09-25
     */
    @RequestMapping("/addItem")
    @ResponseBody
    public ResponseData addItem(TaoGoodCartParam taoGoodCartParam) {
        this.taoGoodCartService.add(taoGoodCartParam);
        return ResponseData.success();
    }

    /**
     * 购物车查看选中的商品
     *
     * @author lcw
     * @Date 2019-09-25
     */
    @RequestMapping("/getgoodCartbyphone")
    @ResponseBody
    public ResponseData getgoodCartbyphone(TaoGoodCartParam taoGoodCartParam) {
        ResponseData data = new ResponseData();
        List<Map<String, Object>> detail = taoGoodCartService.getgoodCartbyphone(taoGoodCartParam.getWxUserPhone());
        data.setData(detail);
        return ResponseData.success(data);
    }

    /**
     * 删除购物车
     *
     * @author lcw
     * @Date 2019-09-25
     */
    @RequestMapping("/deleteBygoodId")
    @ResponseBody
    public ResponseData deleteBygoodId(String goodId,String openId) {
        taoGoodCartService.deleteBygoodId(goodId,openId);
        return ResponseData.success();
    }

    /**
     * 订单完成后删除购物车
     *
     * @author lcw
     * @Date 2019-09-25
     */
    @RequestMapping("/deleteByType")
    @ResponseBody
    public ResponseData deleteByType(TaoGoodCartParam param) {
        taoGoodCartService.deleteByType(param);
        return ResponseData.success();
    }

    /**
     * 增加订单
     */
    @RequestMapping("/addOrders")
    @ResponseBody
    public void addOrders(TbOrderParam tbOrderParam){
        String[] goodsId = tbOrderParam.getGoodsId().split(",");
        String[] quantity = tbOrderParam.getQuantity().split(",");
        for (int i= 0;i<goodsId.length;i++) {
            tbOrderParam.setGoodsId(goodsId[i]);
            tbOrderParam.setQuantity(quantity[i]);
            tbOrderService.addOrder(tbOrderParam);
        }
    }

    /**
     * 删除订单
     */
    @RequestMapping("/deleteOrders")
    @ResponseBody
    public void deleteOrders(TbOrderParam tbOrderParam){
        String[] orderId = tbOrderParam.getOrderId().split(",");
        for (int i= 0;i<orderId.length;i++) {
            tbOrderParam.setOrderId(orderId[i]);
            tbOrderService.deleteOrders(tbOrderParam);
        }
    }

    /**
     * 修改订单状态（付款,退货等等）
     */
    @RequestMapping("/updateOrders")
    @ResponseBody
    public void updateOrders(TbOrderParam tbOrderParam){
        tbOrderService.updateOrders(tbOrderParam);
    }

    /**
     * 查询全部或特定订单
     *
     * @author zhou
     * @Date 2019-08-02
     */
    @ResponseBody
    @RequestMapping("/orderList")
    public ResponseData orderList(String userId,String status) {
        String id = "";
        ResponseData data = new ResponseData();
        List<Map<String, Object>> detail = tbOrderService.getOrderList(userId,status);
        data.setData(detail);
        Map<String ,Object> map = new HashMap();
        for(int i = 0 ; i<detail.size(); i++){
            id+=detail.get(i).get("id").toString()+",";
        }
        map.put("data",data);
        map.put("ids",id);
        return ResponseData.success(data);
    }

    /**
     * 查询特定订单
     *
     * @author zhou
     * @Date 2019-08-02
     */
    @ResponseBody
    @RequestMapping("/orderbyOrderid")
    public ResponseData orderbyOrderid(String userId,String status) {
        ResponseData data = new ResponseData();
        List<Map<String, Object>> detail = tbOrderService.getOrderList(userId,status);
        data.setData(detail);
        return ResponseData.success(data);
    }

    /**
     * 轮播（热门商品）
     *
     * @author lcw
     * @Date 2019-09-27
     */
    @ResponseBody
    @RequestMapping("/list")
    public ResponseData list(TaoIndexPicParam taoIndexPicParam) throws ParseException {
        Date date = new Date();
        DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
        DateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        String stringDate = sdf.format(date);

        //SimpleDateFormat sdfs = new SimpleDateFormat("yyyy-MM-dd");
        //String stringDateOn = sdf.format(date);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, 1); //把日期往后增加一年，整数往后推，负数往前移
        date = calendar.getTime();
        String stringDateOff = sdf.format(date);//date-->String

        WxUser wxuser = new WxUser();
        List<WxUser> list = wxUserService.memberGrade(wxuser);
        if(list.size()>0){
            for (int i = 0;i<list.size();i++){
                if(list.get(i).getTimeOff() !=null &&dateFormat.parse(stringDate).after(dateFormat.parse(list.get(i).getTimeOff()))){
                    wxuser.setOpenId(list.get(i).getOpenId());
                    wxuser.setMemberGrade(list.get(i).getMemberGrade());
                    wxuser.setQuotaMoney(list.get(i).getQuotaMoney());
                    wxuser.setMemberMoney(list.get(i).getMemberMoney());
                    wxuser.setNumberOn(list.get(i).getNumberOn());
                    wxuser.setNumberOff(list.get(i).getNumberOff());
                    wxuser.setTimeOn(stringDate);
                    wxuser.setTimeOff(stringDateOff);
                    wxuser.setIsMember(list.get(i).getIsMember());
                    wxUserService.upgradeMember(wxuser);
                }
                if(list.get(i).getNumberOff() !=null &&dateFormat.parse(stringDate).after(dateFormat.parse(list.get(i).getNumberOff()))){
                    wxuser.setMemberGrade("0");
                    wxuser.setOpenId(list.get(i).getOpenId());
                    wxuser.setUseMoney(list.get(i).getUseMoney());
                    wxuser.setTimeOn(list.get(i).getTimeOn());
                    wxuser.setTimeOff(list.get(i).getTimeOff());
                    wxuser.setIsMember(list.get(i).getIsMember());
                    wxUserService.upgradeMember(wxuser);
                }
            }
        }

        ResponseData data = new ResponseData();
        List<TaoIndexPicResult> detail = taoIndexPicService.findListBySpec(taoIndexPicParam);
        data.setData(detail);
        return ResponseData.success(data);
    }

    /**
     * 查看优惠券
     *
     * @author lcw
     * @Date 2019-09-27
     */
    @ResponseBody
    @RequestMapping("/couponList")
    public ResponseData couponList(CouponParam couponParam) {
        ResponseData data = new ResponseData();
        List<CouponResult> detail = couponService.findListBySpec(couponParam);
        data.setData(detail);
        return ResponseData.success(data);
    }

    /**
     * 查看自己领取的优惠券
     *
     * @author lcw
     * @Date 2019-09-27
     */
    @ResponseBody
    @RequestMapping("/couponbyOpen_id")
    public ResponseData couponbyOpen_id(CouponLeadParam couponLeadParam) {
        ResponseData data = new ResponseData();
        List<CouponLeadResult> detail = couponLeadService.findListBySpec(couponLeadParam);
        data.setData(detail);
        return ResponseData.success(data);
    }


    /**
     * 领取优惠券
     *
     * @author
     * @Date 2019-08-21
     */
    @RequestMapping("/addCoupon")
    @ResponseBody
    public ResponseData addCoupon(CouponLeadParam couponLeadParam) {
        List<CouponResult> list =  couponService.couponById(couponLeadParam.getCouponId());
        int num = 0;
        if (list.get(0).getSendNumber()>0){
            num = list.get(0).getSendNumber()-1;
        }
        CouponParam couponParam = new CouponParam();
        couponParam.setSendNumber(num);
        couponParam.setId(couponLeadParam.getCouponId());
        couponService.updateCoupons(couponParam);
        this.couponLeadService.addCoupon(couponLeadParam);
        return ResponseData.success();
    }


    /**
     * 删除优惠券
     *
     * @author
     * @Date 2019-08-21
     */
    @RequestMapping("/deleteCoupon")
    @ResponseBody
    public ResponseData deleteCoupon(CouponLeadParam couponLeadParam) {
        this.couponLeadService.deleteCoupon(couponLeadParam);
        return ResponseData.success();
    }

    /**
     * 使用优惠券
     *
     * @author
     * @Date 2019-08-21
     */
    @RequestMapping("/updateCoupon")
    @ResponseBody
    public ResponseData updateCoupon(CouponLeadParam couponLeadParam) {
        this.couponLeadService.updateCoupon(couponLeadParam);
        return ResponseData.success();
    }

    /**
     * 查询曾经是否是会员
     */
    @RequestMapping("/isMember")
    @ResponseBody
    public ResponseData isMember(WxUser wxuser){
        ResponseData data = new ResponseData();
        List<WxUser> detail = wxUserService.memberTime(wxuser);
        data.setData(detail.get(0).getIsMember());
        return ResponseData.success(data);
    }

    /**
     * 升级会员或体验会员
     */
    @RequestMapping("/upgradeMember")
    @ResponseBody
    public void upgradeMember(WxUser wxuser){
        if(!wxuser.getMemberGrade().equals("4")){
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String stringDate = sdf.format(date);
            wxuser.setNumberOn(stringDate);
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(Calendar.YEAR, 1); //把日期往后增加一年，整数往后推，负数往前移
            date = calendar.getTime();
            stringDate = sdf.format(date);//date-->String
            wxuser.setNumberOff(stringDate);
            }
        wxuser.setIsMember(1);
        wxUserService.upgradeMember(wxuser);
    }

    /**
     * B端授权会员
     */
    @RequestMapping("/shouQuan")
    @ResponseBody
    public String shouQuan(WxUser wxuser){
        if(weiXinOrderService.WeiUser(wxuser).size()==0){
            //未注册
            return "n" ;
        }
        if(wxUserService.isGrant(wxuser).size()>0){
            //已授权
            return "g" ;
        }
        wxuser.setIsMember(1);
        wxUserService.shouQuan(wxuser);
        //授权成功
        return "y" ;
    }

    /**
     * 查询已使用金额
     */
    @RequestMapping("/useMoney")
    @ResponseBody
    public ResponseData useMoney(WxUser wxuser){
        ResponseData data = new ResponseData();
        List<WxUser> detail = wxUserService.userMoney(wxuser);
        data.setData(detail.get(0).getQuotaMoney());
        return ResponseData.success(data);
    }

    /**
     * 查询授权会员的人员信息
     */
    @RequestMapping("/grantMember")
    @ResponseBody
    public ResponseData grantMember(WxUser wxuser){
        ResponseData data = new ResponseData();
        List<WxUser> detail = wxUserService.grantMember(wxuser);
        data.setData(detail);
        return ResponseData.success(data);
    }

    /**
     * 查询用户会员
     *getProductDetail
     * @author lcw
     * @Date 2019-09-27';fslsr
     */
    @ResponseBody
    @RequestMapping("/memberGrade")
    public ResponseData memberGrade(WxUser wxuser) {
        ResponseData data = new ResponseData();
        List<WxUser> detail = wxUserService.memberGrade(wxuser);
        data.setData(detail);
        return ResponseData.success(data);
    }


    /**
     * 通过 openid 查询用户推广码 只返回推广码
     */
    @ResponseBody
    @RequestMapping("/queryZationCode")
    public ResponseData queryZationCode(WxUser wxuser) {
        QueryWrapper<TaoWxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("open_id",wxuser.getOpenId());
        List<TaoWxUser> list = taoWxUserService.list(queryWrapper);
        for (TaoWxUser li : list) {
            wxuser.setGeneralizationCode(li.getGeneralizationCode());
        }
        return ResponseData.success(wxuser.getGeneralizationCode());
    }


    /**
     * 通过邀请码邀请用户注册
     */
    @ResponseBody
    @RequestMapping("/invitationRegistration")
    public ResponseData invitationRegistration(WxUser wxuser) {
        /**
         * 通过邀请码查询 表的 id 把表的 id 存入推广者的 id
         */
        QueryWrapper<TaoWxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("generalization_code",wxuser.getGeneralizationCode());
        List<TaoWxUser> list = taoWxUserService.list(queryWrapper);
        for (TaoWxUser tu: list) {
            wxuser.setPromoterId(tu.getId());
        }

        if(weiXinOrderService.WeiUser(wxuser).size()>0){
            return null;
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String stringDate = sdf.format(date);
        wxuser.setTimeOn(stringDate);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, 1); //把日期往后增加一年，整数往后推，负数往前移
        date = calendar.getTime();
        stringDate = sdf.format(date);//date-->String
        wxuser.setTimeOff(stringDate);

        /**
         * 注册时生成 把推广码 存储到被推广码里面
         */
        wxuser.setGeneralizationCode(wxuser.getGeneralizationCode());

        weiXinOrderService.zhuce(wxuser);

        return ResponseData.success();
    }



    /**
     *
     * @return URL 所代表远程资源的响应结果
     *
     * 用户同意授权，获取code
     */
    @RequestMapping("/authorize")
    @ResponseBody
    public void authorize(HttpServletResponse response) throws IOException {
        String appid = "wx7a87fd6bafc0dfef";
        String uri = urlEncodeUTF8("http://bgigclub.com/pages/user/user");
        String urlNameString = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid+"&redirect_uri="+uri+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        response.sendRedirect(urlNameString.replace("APPID",appid).replace("REDIRECT_URL",uri).replace("SCOPE","snsapi_userinfo"));
    }

    /**
     * 获取网页授权凭证
     *
     * @param code
     * @return WeixinAouth2Token
     */
    @RequestMapping("/getOauth2AccessToken")
    @ResponseBody
    public static Oauth2Token getOauth2AccessToken(String code) {
        Oauth2Token wat = null;
        String appId = "wx7a87fd6bafc0dfef";
        String appSecret = "c9bda4afe26a0a2cb45902fd3e69ec58";
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
        requestUrl = requestUrl.replace("APPID", appId);
        requestUrl = requestUrl.replace("SECRET", appSecret);
        requestUrl = requestUrl.replace("CODE", code);
        // 获取网页授权凭证
        com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(NetUtil.get(requestUrl));
        if (null != jsonObject) {
            try {
                wat = new Oauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                //wat.setExpiresIn(jsonObject.getInteger("expires_in"));
                //wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setScope(jsonObject.getString("scope"));
            } catch (Exception e) {
                wat = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");
            }
        }
        return wat;
    }

    /**
     * 通过网页授权获取用户信息
     *
     * @param accessToken 网页授权接口调用凭证
     * @param openId 用户标识
     * @return SNSUserInfo
     */
    @RequestMapping("/getSNSUserInfo")
    @ResponseBody
    public static SNSUserInfo getSNSUserInfo(String accessToken, String openId) {
        SNSUserInfo snsUserInfo = null;
        // 拼接请求地址
        String requestUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID";
        requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("OPENID", openId);
        // 通过网页授权获取用户信息
        com.alibaba.fastjson.JSONObject jsonObject =  JSON.parseObject(NetUtil.get(requestUrl));

        if (null != jsonObject) {
            try {
                snsUserInfo = new SNSUserInfo();
                // 用户的标识
                snsUserInfo.setOpenId(jsonObject.getString("openid"));
                // 昵称
                snsUserInfo.setNickname(jsonObject.getString("nickname"));
                // 性别（1是男性，2是女性，0是未知）
                snsUserInfo.setSex(jsonObject.getInteger("sex"));
                // 用户所在国家
                snsUserInfo.setCountry(jsonObject.getString("country"));
                // 用户所在省份
                snsUserInfo.setProvince(jsonObject.getString("province"));
                // 用户所在城市
                snsUserInfo.setCity(jsonObject.getString("city"));
                // 用户头像
                snsUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
                // 用户特权信息
                List<String> list = JSON.parseArray(jsonObject.getString("privilege"),String.class);
                snsUserInfo.setPrivilegeList(list);
                //与开放平台共用的唯一标识，只有在用户将公众号绑定到微信开放平台帐号后，才会出现该字段。
                snsUserInfo.setUnionid(jsonObject.getString("unionid"));
            } catch (Exception e) {
                snsUserInfo = null;
                int errorCode = jsonObject.getInteger("errcode");
                String errorMsg = jsonObject.getString("errmsg");
            }
        }
        return snsUserInfo;
    }

    /**
     * URL编码（utf-8）
     *
     * @param source
     * @return
     */
    public static String urlEncodeUTF8(String source) {
        String result = source;
        try {
            result = java.net.URLEncoder.encode(source, "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取Ticket
     * @param accessToken
     * @return
     */
    @RequestMapping("/getTicket")
    @ResponseBody
    public String getTicket(String accessToken) {
        // 网页授权接口
        String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
        HttpClient client = null;
        String ticket = "";
        int expires_in = 0;
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(GetPageAccessTokenUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.fromObject(response);
            ticket = String.valueOf(OpenidJSONO.get("ticket"));//获取ticket
            expires_in = Integer.parseInt(String.valueOf(OpenidJSONO.get("expires_in")));//获取时间
        } catch (Exception e) {
            //throw new CommonRuntimeException("获取Ticket出错！");
        } finally {
            client.getConnectionManager().shutdown();
        }

        return ticket;
    }

    /**
     * SHA1加密，参数是由url、jsapi_ticket、noncestr、timestamp组合而成
     * @return
     */
    @RequestMapping("/SHA1")
    @ResponseBody
    public String SHA1(String str) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可getInstance("SHA");
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexStr = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexStr.append(0);
                }
                hexStr.append(shaHex);
            }
            return hexStr.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取 AccessToken
     * @return
     */
    @RequestMapping("/getAccessToken")
    @ResponseBody
    public String getAccessToken(String appId , String appSecret){
        // 网页授权接口
        String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;

        HttpClient client = null;
        String access_token = null;
        int expires_in = 0;
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(GetPageAccessTokenUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.fromObject(response);
            access_token = String.valueOf(OpenidJSONO.get("access_token"));//获取access_token
            expires_in = Integer.parseInt(String.valueOf(OpenidJSONO.get("expires_in")));//获取时间
        } catch (Exception e) {
            //throw new CommonRuntimeException("获取AccessToken出错！");
        } finally {
            client.getConnectionManager().shutdown();
        }
        return access_token;
    }

    /**
     * 获取 Signature
     * @return
     */
    @RequestMapping("/getSignature")
    @ResponseBody
    public Map<String, Object> getSignature(String url) {

        String signature = "";
        Map<String, Object> map = new HashMap();
        String appId = "wx7a87fd6bafc0dfef";
        String appSecret = "c9bda4afe26a0a2cb45902fd3e69ec58";

        //获取noncestr
        //String noncestr = UUID.randomUUID().toString();
        String noncestr = getGUID();
        //获取timestamp
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        //获取access_token
        String access_token = getAccessToken(appId , appSecret);
        //获取jspai_ticket
        String jsapi_ticket = getTicket(access_token);
        //将四个数据进行组合，传给SHA1进行加密
        String str = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + noncestr +
                "&timestamp=" + timestamp +
                "&url=" + url;

        //sha1加密
        signature = SHA1(str);
        map.put("signature",signature);
        map.put("noncestr",noncestr);
        map.put("timestamp",timestamp);
        map.put("jsapi_ticket",jsapi_ticket);
        System.out.print(str);
        System.out.print("签名"+signature);
        return map ;
    }

    /**
     * 获取随机16位随机数
     * @return
     */
    @RequestMapping("/getGUID")
    @ResponseBody
    public static String getGUID() {
        StringBuilder uid = new StringBuilder();
        //产生16位的强随机数
        Random rd = new SecureRandom();
        for (int i = 0; i < 16; i++) {
            //产生0-2的3位随机数
            int type = rd.nextInt(3);
            switch (type){
                case 0:
                    //0-9的随机数
                    uid.append(rd.nextInt(10));
                    break;
                case 1:
                    //ASCII在65-90之间为大写,获取大写随机
                    uid.append((char)(rd.nextInt(25)+65));
                    break;
                case 2:
                    //ASCII在97-122之间为小写，获取小写随机
                    uid.append((char)(rd.nextInt(25)+97));
                    break;
                default:
                    break;
            }
        }
        return uid.toString();
    }
//////////////////////////////////////////////////////////////////////////////////////////////////



    /**
     * 微信异步回调通知
     * @param request
     * @param response
     * @return
     */
    //@ExceptionHandler(value = Exception.class)
    @ResponseBody
    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    public String notify(HttpServletRequest request,HttpServletResponse response){

        String inputLine;
        String notifyXml = "";
        String concat = "";

        //Map<String, Object> retMap = new HashMap<String, Object>();

        try {
            while ((inputLine = request.getReader().readLine()) != null){
                notifyXml += inputLine;
            }
            Map<String, String> notifyMap = WXPayUtil.xmlToMap(notifyXml);//将微信发的xml转map
            String openId = notifyMap.get("openid");
            if(notifyMap.get("return_code").equals("SUCCESS")){
                //retMap.put("result_code", "SUCCESS");
                concat = "SUCCESS";

            }else {
                concat = "file";
            }
            taoWxUserService.updateNotify(concat,openId);
            //告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
            String resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
            outs.write(resXml.getBytes());
            outs.flush();
            outs.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return concat;
    }


    /**
     *
     *
     * @return
     */
    @ResponseBody
    @RequestMapping("/selectNotify")
    public ResponseData selectNotify(String openId){

        String notify = "SUCCESS";
        int num = taoWxUserService.number(notify,openId);
        notify = "file";
        taoWxUserService.updateNotify(notify,openId);

        return ResponseData.success(num);
    }

    /**
     * 根据地市查询运费
     */
    @RequestMapping("/moenyByCity")
    @ResponseBody
    public ResponseData moenyByCity(TbFreightParam tbFreightParam) {
        List<TbFreightResult> list =  tbFreightService.moenyByCity(tbFreightParam);
        String money  = "";
        if(list.size() != 0){
            money  = list.get(0).getName();
        }
        return ResponseData.success(money.replace("元",""));
    }

    /**
     * 首页自定义展示
     *
     * @author lcw
     * @Date 2019-11-18
     */
    @ResponseBody
    @RequestMapping("/getIndexGoods")
    public ResponseData getIndexGoods(TaoRecommendGoodsParam taoRecommendGoodsParam) {
        List<TaoRecommendGoodsResult> list = taoRecommendGoodsService.getIndexGoods(taoRecommendGoodsParam);
        return ResponseData.success(list);
    }

    /**
     * 首页商品查询(商品)
     */
    @RequestMapping("/getGoodsById")
    @ResponseBody
    public ResponseData getGoodsById(TaoRecommendGoodsParam taoRecommendGoodsParam){
        List<TaoRecommendGoodsResult> list = taoRecommendGoodsService.getGoodsById(taoRecommendGoodsParam);
        return ResponseData.success(list);
    }

    /**
     * 首页商品查询(分类)
     */
    @RequestMapping("/getGoodsByType")
    @ResponseBody
    public ResponseData getGoodsByType(TaoRecommendGoodsParam taoRecommendGoodsParam){
        List<TaoRecommendGoodsResult> list = taoRecommendGoodsService.getGoodsByType(taoRecommendGoodsParam);
        return ResponseData.success(list);
    }
}






